<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;
use App\Models\Issue;

class FetchIssueImg extends Command
{

    const ISSUE_URL = "http://www.zoores.ac.cn/EN/volumn/volumn_%u.shtml";
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch:issue_img {id?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'download issue cover';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $id = $this->argument('id');
        if ($id) {
            $this->processIssue($id);
        } else {

            $page = 1;
            $count = 0;
            while (true) {
                $issues = Issue::simplePaginate(5, ['*'], 'page', $page);
                $break = (bool)(count($issues->items()) == 0);

                foreach ($issues as $issue) {
                    $this->processIssue($issue->zr_id);
                    $count ++;

                    $this->info($count . ' issues cover downloaded.');
                }
                if ($break) break;
                
                $page++;
            }

            $this->info('Done for ' . $count . 'issues.');
        }
    }


    public function processIssue($id)
    {
        if ($id == 0) {
            return null;
        }
        $url = sprintf(self::ISSUE_URL, $id);
        try {

            $this->info('Downloading the cover of issue: ' . $id);

            $client = new Client();
            $guzzleClient = new GuzzleClient(array(
                'timeout' => 60,
            ));
            $client->setClient($guzzleClient);
            $crawler = $client->request('GET', $url);
            $imageUrl = $crawler->filterXpath('//div[@class="zj_right"]//img')->eq(0)->image()->getUri();

            if ($imageUrl) {
                $fileInfo = pathinfo($imageUrl);
                $issue = Issue::where('zr_id', $id)->first();
                if (!isset($fileInfo['extension']) ||  !$fileInfo['extension']) {
                    $this->info('skipped the issue, zr id: ' . $id);
                    return null;
                }
                $fileName = config('admin.upload.directory.image') . '/' . 'zr_issue_cover_' . $issue->id . '.' . $fileInfo['extension'];
                $file = $file = public_path('uploads/') . $fileName;

                $response = $client->getClient()->get($imageUrl, [
                    'save_to' => $file
                ]);

                $issue->cover = $fileName;
                $issue->cover_en = $fileName;
                $issue->save();
            
                $this->info('Downloaded the cover of issue: ' . $id);

            }

            // $client = 
        } catch (\Exception $e) {
            print_r($e->getMessage());
        }

    }
}
